import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { observer } from 'mobx-react';

import ContentLayout from '@/component/common/ContentLayout';
import MTable from '@/component/common/MTable';
import { Pagination, Form, Input, Select, message, Spin, DatePicker } from 'antd';
import MModal from '@/component/common/MModal';
import FilterListPage from '@/component/common/FilterListPage';
import format from '@/tool/format';
import helper from '@/tool/helper';

const FormItem = Form.Item;
const Option = Select.Option;
const mConfirm = MModal.confirm;
const { RangePicker } = DatePicker;

import style from './style.scss';

import StoreListMini from '@/store/StoreListMini';
import BrokerListMini from '@/store/BrokerListMini';
import adminType from '@/tool/adminType';

import { lock_list as api_lock_list, lock_record as api_lock_record,
    lock_user_list as api_lock_user_list, lock_key_freeze, lock_key_unfreeze, lock_key_delete,
    lock_send_key, broker_list_mini, repair_address_list,
    lock_bind, lock_unbind, buy_lock_apply } from '@/constants/ApiTypes';
import ApiHelper from "../../store/ApiHelper";

//智能锁绑定
class LockBindModal extends Component {
    static propTypes = {
        visible: PropTypes.bool,
        onClose: PropTypes.func.isRequired,
        lock_id: PropTypes.string.isRequired,
        owner_uid: PropTypes.any.isRequired
    };
    defaultState = {
        store_id: '',
        broker_id: '',
        spinning: false,
        broker_list: [],
        address_list: [],
        house_no: ''
    };
    state = this.defaultState;
    componentWillReceiveProps(nextProps) {
        if (nextProps.visible) {
            this.setState(this.defaultState);
        }
    }
    componentDidMount() {
        this._isMounted = true;
    }
    componentWillUnmount() {
        this._isMounted = false;
    }
    //fix异步
    _setState = state => {
        if (this._isMounted) this.setState(state);
    };
    selectStore = async value => {
        if (value == '') {
            return this._setState({ broker_list: [], store_id: value });
        }
        let data = { store_id: value };
        const result = await ApiHelper.requestPost(broker_list_mini, data);
        if (result.status) {
            this._setState({
                store_id: value,
                broker_id: '',
                broker_list: result.info,
                address_list: []
            });
        }
    };
    selectBroker = async value => {
        const data = { uid: value };
        const result = await ApiHelper.requestPost(repair_address_list, data);
        if (result.status) {
            this._setState({
                broker_id: value,
                address: '',
                address_list: result.info
            });
        }
    };
    selectAddress = value => {
        this._setState({ house_no: value });
    };
    onSubmit = async () => {
        const { owner_uid, lock_id } = this.props;
        const { house_no } = this.state;
        if (house_no == '') {
            return message.warn('请选择绑定房源！');
        }
        const data = {
            owner_uid, lock_id, house_no
        };
        this._setState({ spinning: true });
        const result = await ApiHelper.requestPost(lock_bind, data);
        this._setState({ spinning: false });
        if (result.status) {
            MModal.success({ title: '操作成功', content: '绑定成功' });
            this.props.onClose(true);
        } else {
            MModal.success({ title: '操作失败', content: result.info });
        }
    };
    render() {
        const { visible, onClose } = this.props;
        const { store_id, broker_id, house_no, address_list, broker_list, spinning } = this.state;
        const storeListMini = StoreListMini.info;

        let storeOptionList = storeListMini.map((val, index) => {
            return <Option key={index} value={`${val.store_id}`}>{val.store_name}</Option>;
        });
        let brokerOptionList = broker_list.map((val, index) => {
            return <Option key={index} value={`${val.uid}`}>{val.realname}</Option>;
        });
        let addressOptionList = address_list.map((val, index) => {
            return <Option key={index} value={val.house_no}>{val.address_detail}</Option>;
        });
        return (
            <MModal visible={visible} onClose={onClose} showMask closeMaskOnClick={false} width={815} height={200}>
                <Spin spinning={spinning} delay={150}>
                    <div className={style['lock-bind-modal']}>
                        <div className={style['select-wrap']}>
                            <div className={style['label-item']}>
                                <span className={style['label-text']}>门店：</span>
                                <Select placeholder="选择门店" style={{ width: 150 }} onChange={this.selectStore} value={store_id}>
                                    {storeOptionList}
                                </Select>
                            </div>
                            <div className={style['label-item']}>
                                <span className={style['label-text']}>经纪人：</span>
                                <Select placeholder="选择经纪人" style={{ width: 100 }} value={broker_id} onChange={this.selectBroker}>
                                    {brokerOptionList}
                                </Select>
                            </div>
                            <div className={style['label-item']}>
                                <span className={style['label-text']}>地址：</span>
                                <Select placeholder="选择地址" value={house_no} style={{ width: 260 }} onChange={this.selectAddress}>
                                    {addressOptionList}
                                </Select>
                            </div>
                        </div>
                        <div className={style['submit']}>
                            <a href="javascript:void(0);" className={style['submit-btn']} onClick={this.onSubmit}>提交</a>
                        </div>
                    </div>
                </Spin>
            </MModal>
        );
    }
}

//用户管理
class UserManagerModal extends FilterListPage {
    constructor(props) {
        super(props);
        this.defaultQuery = {
            per_page: 8
        };
    }
    static propTypes = {
        visible: PropTypes.bool,
        onClose: PropTypes.func.isRequired,
        lock_id: PropTypes.string.isRequired
    };
    componentWillReceiveProps(nextProps) {
        if (nextProps.visible) {
            this.listApiType = api_lock_user_list;
            this.getDataListWithFilter({ lock_id: nextProps.lock_id });
        }
    }
    operFreeze = (key_id, owner_uid) => {
        mConfirm({
            title: '确定要冻结该钥匙吗？',
            titleStyle: { fontSize: 16 },
            width: 300,
            height: 177,
            content: '',
            okText: '是',
            cancelText: '否',
            okClassName: 'primary-btn-ok',
            cancelClassName: 'primary-btn-cancel',
            showTopClose: false,
            onOk: async () => {
                const data = { key_id, owner_uid };
                const result = await ApiHelper.requestPost(lock_key_freeze, data);
                if (result.status) {
                    MModal.success({ title: '操作成功', content: '冻结该钥匙成功' });
                    this.refresh();
                } else {
                    MModal.success({ title: '操作失败', content: result.info });
                }
            },
            onCancel() {}
        });
    };
    operUnfreeze = (key_id, owner_uid) => {
        mConfirm({
            title: '确定要解冻该钥匙吗？',
            titleStyle: { fontSize: 16 },
            width: 300,
            height: 177,
            content: '',
            okText: '是',
            cancelText: '否',
            okClassName: 'primary-btn-ok',
            cancelClassName: 'primary-btn-cancel',
            showTopClose: false,
            onOk: async () => {
                const data = { key_id, owner_uid };
                const result = await ApiHelper.requestPost(lock_key_unfreeze, data);
                if (result.status) {
                    MModal.success({ title: '操作成功', content: '解冻该钥匙成功' });
                    this.refresh();
                } else {
                    MModal.success({ title: '操作失败', content: result.info });
                }
            },
            onCancel() {}
        });
    };
    operDelete = (lock_id, key_id, owner_uid) => {
        mConfirm({
            title: '确定要删除该钥匙吗？',
            titleStyle: { fontSize: 16 },
            width: 300,
            height: 177,
            content: '',
            okText: '是',
            cancelText: '否',
            okClassName: 'primary-btn-ok',
            cancelClassName: 'primary-btn-cancel',
            showTopClose: false,
            onOk: async () => {
                const data = { lock_id, key_id, owner_uid };
                const result = await ApiHelper.requestPost(lock_key_delete, data);
                if (result.status) {
                    MModal.success({ title: '操作成功', content: '删除该钥匙成功' });
                    this.refresh();
                } else {
                    MModal.success({ title: '操作失败', content: result.info });
                }
            },
            onCancel() {}
        });
    };
    render() {
        const { visible, onClose } = this.props;
        // const testUserData = [
        //     { a: 'D8:EU:LO:T6', b: '16542683484181', c: '普通', d: '正常', e: '永久', f: '2017/10/21 10:24:08', isFrozen: true },
        //     { a: 'D8:EU:LO:T6', b: '16542683484181', c: '普通', d: '正常', e: '永久', f: '2017/10/21 10:24:08', isFrozen: false }
        // ];
        const oper = (text, record, dataIndex) => {
            const status_types = {
                110401: '钥匙正常',
                110402: '钥匙等待接收',
                110405: '钥匙冻结',
                110408: '钥匙删除',
                110410: '钥匙重置'
            };
            const status_type =  record.status in status_types ? status_types[record.status] : '未知';
            let op;
            if (status_type == '钥匙正常') {
                op = <a className={style['btn-warn']} href="javascript:void(0);" onClick={() => this.operFreeze(record.key_id, record.owner_uid)}>冻结</a>;
            }
            if (status_type == '钥匙冻结') {
                op = <a className={style['btn-success']} href="javascript:void(0);" onClick={() => this.operUnfreeze(record.key_id, record.owner_uid)}>解冻</a>;
            }
            return (
                <div>
                    {op}
                    <a className={style['btn-default']} href="javascript:void(0);" onClick={() => this.operDelete(record.lock_id, record.key_id, record.owner_uid)}>删除</a>
                </div>
            );
        };
        const use_date = (text, record, dataIndex) => {
            const start = record.start == 0 ? '∞' : format.timeString(record.start);
            const end = record.end == 0 ? '∞' : format.timeString(record.end);
            return `${start} - ${end}`;
        };
        const columns = [
            { title: '钥匙ID', dataIndex: 'key_id', align: 'middle' },
            { title: '用户', dataIndex: 'nickname', align: 'middle' },
            { title: '类型', dataIndex: 'type_desc', align: 'middle' },
            { title: '状态', dataIndex: 'key_status', align: 'middle' },
            { title: '有效期', dataIndex: 'e', align: 'middle', render: use_date },
            { title: '生成时间', dataIndex: 'create_time', align: 'middle', render: (text, record, dataIndex) => format.timeString(text) },
            { title: '操作', dataIndex: 'g', align: 'middle', render: oper }
        ];
        return (
            <MModal visible={visible} onClose={onClose} showMask closeMaskOnClick={false} width={1100} height={helper.fixHeight(600)}>
                <div className={style['table-modal']}>
                    <h1 className={style['title']}>用户管理</h1>
                    <MTable columns={columns} dataSource={this.state.dataList} spinning={this.state.spinning}/>
                    <div className="pagination">
                        {this.state.total > 0 && <Pagination showQuickJumper current={this.state.current_page} pageSize={10} total={this.state.total} onChange={this.pageOnChange} />}
                    </div>
                </div>
            </MModal>
        );
    }
}

//开锁记录
class LockHistoryModal extends FilterListPage {
    constructor(props) {
        super(props);
        this.defaultQuery = {
            per_page: 8
        };
    }
    static propTypes = {
        visible: PropTypes.bool,
        onClose: PropTypes.func.isRequired,
        lock_id: PropTypes.string.isRequired
    };
    componentWillReceiveProps(nextProps) {
        if (nextProps.visible) {
            this.listApiType = api_lock_record;
            this.getDataListWithFilter({ lock_id: nextProps.lock_id });
        }
    }
    render() {
        const { visible, onClose } = this.props;
        // const testUserData = [
        //     { a: '2017/10/21 10:24:08', b: 'APP开锁', c: '奋斗琪琪', d: '成功' },
        //     { a: '2017/10/21 10:24:08', b: '键盘密码开锁', c: '16542683484181', d: '成功' }
        // ];

        const _time = (text, record, dataIndex) => {
            return format.timeString(record.open_op_time) + '/' + format.timeString(record.open_create_time);
        };
        const columns = [
            { title: '开锁时间/服务器时间', dataIndex: 'a', align: 'middle', render: _time },
            { title: '开锁类型', dataIndex: 'open_type', align: 'middle' },
            { title: '开锁用户/键盘密码', dataIndex: 'c', align: 'middle',
                render: (text, record, dataIndex) => record.open_type == 'APP开锁' ? record.op_user : record.key_psw },
            { title: '是否成功', dataIndex: 'result', align: 'middle' }
        ];
        return (
            <MModal visible={visible} onClose={onClose} showMask closeMaskOnClick={false} width={1100} height={helper.fixHeight(600)}>
                <div className={style['table-modal']}>
                    <h1 className={style['title']}>开锁记录</h1>
                    <MTable columns={columns} dataSource={this.state.dataList} spinning={this.state.spinning}/>
                    <div className="pagination">
                        {this.state.total > 0 && <Pagination showQuickJumper current={this.state.current_page} pageSize={10} total={this.state.total} onChange={this.pageOnChange} />}
                    </div>
                </div>
            </MModal>
        );
    }
}

//购买智能锁
class BuyLockModal extends Component {
    static propTypes = {
        visible: PropTypes.bool,
        onClose: PropTypes.func.isRequired
    };
    defaultState = {
        address: '',
        linkman: '',
        tel_phone: '',
        number: 0,
        spinning: false
    };
    state = this.defaultState;
    componentWillReceiveProps(nextProps) {
        if (nextProps.visible) {
            this.setState(this.defaultState);
        }
    }
    componentDidMount() {
        this._isMounted = true;
    }
    componentWillUnmount() {
        this._isMounted = false;
    }
    //fix异步
    _setState = state => {
        if (this._isMounted) this.setState(state);
    };
    submitBuyLock = async () => {
        const { address, linkman, tel_phone, number } = this.state;
        if (format.trim(address) == '') {
            this.address_input.focus();
            return message.warn('请填写地址！', 1.5);
        }
        if (format.trim(linkman) == '') {
            this.linkman_input.focus();
            return message.warn('请填写联系人！', 1.5);
        }
        if (format.trim(tel_phone) == '') {
            this.tel_phone_input.focus();
            return message.warn('请填写联系电话！', 1.5);
        }
        if (number <= 0) {
            this.number_input.refs.input.select();
            return message.warn('购买数量必须大于0', 1.5);
        }
        this._setState({ spinning: true });
        const data = {
            apply_name: linkman,
            phone: tel_phone,
            apply_address: address
        };
        const result = await ApiHelper.requestPost(buy_lock_apply, data);
        this._setState({ spinning: false });
        if (result.status) {
            MModal.success({ title: '操作成功', content: result.info });
            this.props.onClose();
        } else {
            MModal.success({ title: '操作失败', content: result.info });
        }
    };
    inputOnChange = e => {
        const name = e.target.name;
        const value = e.target.value;
        if (['address', 'linkman', 'tel_phone'].indexOf(name) > -1) {
            this.setState({ [name]: value });
        }
        if ((name == 'number' && value === '') || (name == 'number' && value < 0)) {
            return this.setState({ number: 0 });
        }
        if (name === 'number' && !isNaN(value)) {
            this.setState({ number: parseInt(value) });
        }
    };
    render() {
        const { visible, onClose } = this.props;
        const { address, linkman, tel_phone, number, spinning } = this.state;
        const { inputOnChange } = this;
        return (
            <MModal visible={visible} onClose={onClose} showMask closeMaskOnClick={false} width={800} height={helper.fixHeight(585)}>
                <Spin spinning={spinning} delay={150}>
                    <div className={style['buy-lock-modal']}>
                        <div className={style['modal-title']}>物流地址</div>
                        <div className={style['label-group']}>
                            <div className={style['label-item']}>
                                <span className={style['label-text']}>地址</span>
                                <Input name="address" ref={input => this.address_input = input} value={address} onChange={inputOnChange}/>
                            </div>
                            <div className={style['label-item']}>
                                <span className={style['label-text']}>联系人</span>
                                <Input name="linkman" ref={input => this.linkman_input = input} value={linkman} onChange={inputOnChange}/>
                            </div>
                            <div className={style['label-item']}>
                                <span className={style['label-text']}>电话</span>
                                <Input name="tel_phone" ref={input => this.tel_phone_input = input} value={tel_phone} onChange={inputOnChange}/>
                            </div>
                        </div>
                        <div className={style['buy-number']}>
                            购买数量<Input name="number" ref={input => this.number_input = input} value={number} onChange={inputOnChange}/>把
                        </div>
                        <div className={style['submit']}>
                            <a href="javascript:void(0);" className={style['submit-btn']} onClick={this.submitBuyLock}>提交</a>
                        </div>
                    </div>
                </Spin>
            </MModal>
        );
    }
}

//发送密码
class SendPswModal extends Component {
    static propTypes = {
        visible: PropTypes.bool,
        onClose: PropTypes.func.isRequired
    };
    render() {
        const { visible, onClose } = this.props;
        return (
            <MModal visible={visible} onClose={onClose} showMask closeMaskOnClick={false} width={1100} height={helper.fixHeight(600)}>
                <div className={style['buy-lock-modal']}>

                </div>
            </MModal>
        );
    }
}
//发送钥匙
class SendKeyModal extends Component {
    static propTypes = {
        visible: PropTypes.bool,
        onClose: PropTypes.func.isRequired,
        owner_uid: PropTypes.any,
        lock_id: PropTypes.string
    };
    defaultState = {
        date_type: '',
        key_type: '1',
        account: ''
    };
    state = this.defaultState;
    componentWillReceiveProps(nextProps) {
        if (nextProps.visible) {
            this.setState(this.defaultState);
        }
    }
    rangePickerOnChange = value => {
        if (value.length == 0) return this.setState({ date_type: '' });
        this.setState({ date_type: value });
    };
    accountInputChange = e => {
        this.setState({ account: e.target.value });
    };
    keyTypeOnchange = value => {
        this.setState({ key_type: value });
    };
    submit = async () => {
        const { key_type, account, date_type } = this.state;
        const { owner_uid, lock_id } = this.props;
        if (key_type == 1 && date_type == '') {
            return message.warn('请选择有效期！');
        }
        if (format.trim(account) == '') {
            this.account_input.refs.input.focus();
            return message.warn('请输入住家账号！');
        }
        const start = Array.isArray(date_type) ? date_type[0].unix() : 0;
        const end = Array.isArray(date_type) ? date_type[1].unix() : 0;

        const data = {
            owner_uid, lock_id, account, start, end
        };
        const result = await ApiHelper.requestPost(lock_send_key, data);
        if (result.status) {
            MModal.success({ title: '操作成功', content: '发送成功' });
            this.props.onClose(true);
        } else {
            MModal.success({ title: '操作失败', content: result.info });
        }
    };
    render() {
        const { visible, onClose } = this.props;
        const { key_type, account } = this.state;
        return (
            <MModal visible={visible} onClose={onClose} showMask closeMaskOnClick={false} width={470} height={270}>
                <div className={style['send-key-modal']}>
                    <div className={style['form-line']}>
                        <div className={style['key_type_item']}>
                            <h3>钥匙类型</h3>
                            <Select size="small" value="2" disabled style={{ width: 80 }}>
                                <Option value="2">租户钥匙</Option>
                            </Select>
                            <Select size="small" value={key_type} onChange={this.keyTypeOnchange} style={{ width: 80, marginLeft: 10 }}>
                                <Option value="1">限时钥匙</Option>
                                <Option value="2">永久钥匙</Option>
                            </Select>
                        </div>
                        {key_type == 1 &&
                        <div className={style['key_type_item']}>
                            <h3>生效时间</h3>
                            <RangePicker style={{ width: 180 }} onChange={this.rangePickerOnChange}/>
                        </div>}
                    </div>
                    <div className={`${style['form-line']} ${style['big-input']}`}>
                        <div className={style['account-label']}>
                            <img src="/static/alliance2/image/lock/zhanghao.png" />
                            <span className={style['label-text']}>账号</span>
                        </div>
                        <Input ref={input => this.account_input = input} placeholder="请输入对方住家账号（手机号）" value={account} onChange={this.accountInputChange} />
                    </div>
                    <div className={style['send-key-oper']}>
                        <a className={style['btn-send']} href="javascript:void(0);" onClick={this.submit}>发送</a>
                    </div>
                </div>
            </MModal>
        );
    }
}

@observer class Filter extends Component {
    static propTypes = {
        form: PropTypes.any,
        buyClick: PropTypes.func.isRequired,
        onSubmit: PropTypes.func
    };
    handleSubmit = e => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                if (this.props.onSubmit) {
                    for (let key in values) {
                        if (values[key] === '') delete values[key];
                        //处理date_range
                        if (key == 'date_range') {
                            if (Array.isArray(values[key]) && values[key].length > 0) {
                                values.start_time = values[key][0].unix();
                                values.end_time =  values[key][1].unix();
                            }
                            delete values[key];
                        }
                    }
                    this.props.onSubmit(values);
                }
            }
        });
    };
    selectStore = value => {
        this.props.form.setFieldsValue({ broker_name: '' });
        if (value == '') {
            return BrokerListMini.info.clear();
        }
        BrokerListMini.getInfo(value);
    };
    render() {
        const { getFieldDecorator } = this.props.form;
        const storeListMini = StoreListMini.info;
        const brokerListMini = BrokerListMini.info;

        let storeOptionList = storeListMini.map((val, index) => {
            return <Option key={index} value={`${val.store_id}`}>{val.store_name}</Option>;
        });
        let brokerOptionList = brokerListMini.map((val, index) => {
            return <Option key={index} value={`${val.realname}`}>{val.realname}</Option>;
        });
        return (
            <Form layout="inline" onSubmit={this.handleSubmit}>
                {adminType() == 1 &&
                <FormItem label="门店">
                    {getFieldDecorator('store_id', {
                        initialValue: ''
                    })(
                        <Select placeholder="选择门店" style={{ width: 150 }} onChange={this.selectStore}>
                            <Option key="default" value="">不限</Option>
                            {storeOptionList}
                        </Select>
                    )}
                </FormItem>}
                <FormItem label="经纪人">
                    {getFieldDecorator('broker_name', {
                        initialValue: ''
                    })(
                        <Select placeholder="选择经纪人" style={{ width: 150 }}>
                            <Option key="default" value="">不限</Option>
                            {brokerOptionList}
                        </Select>
                    )}
                </FormItem>
                <FormItem label="精确查询">
                    {getFieldDecorator('key', {
                        initialValue: ''
                    })(
                        <Input placeholder="锁ID或房源编号"/>
                    )}
                </FormItem>
                <FormItem>
                    <button className={style['submit-btn']} type="submit">搜索</button>
                </FormItem>
                <FormItem>
                    <div className={style['filter-btn']} onClick={this.props.buyClick}><span className={style['filter-plus']} >+</span><span className={style['filter-buy']} href="javascript:void(0);">购买</span></div>
                </FormItem>
            </Form>
        );
    }
}
const FilterWrapped = Form.create()(Filter);

class Battery extends Component {
    static propTypes = {
        percent: PropTypes.any
    };
    render() {
        let { percent } = this.props;
        let imgSrc = '/static/alliance2/image/lock/';
        if (percent >= 1) {
            imgSrc += 'dianchi2.png';
            percent = '1';
        } else if (percent <= 0) {
            imgSrc += 'dianchi5.png';
            percent = '0';
        }
        else if (percent > 0 && percent < 0.6) {
            imgSrc += 'dianchi1.png';
        }
        else if (percent >= 0.6 && percent < 0.8) {
            imgSrc += 'dianchi4.png';
        }
        else if (percent >= 0.8 && percent < 1) {
            imgSrc += 'dianchi3.png';
        }
        return (
            <div className={style['battery']} style={{ backgroundImage: `url(${imgSrc})` }}>
                <span>{parseInt(percent * 100)}%</span>
            </div>
        );
    }
}

@observer class LockList extends FilterListPage {
    constructor(props) {
        super(props);
        const state = {
            buyLockModalVisible: false,
            userManagerModalVisible: false,
            lockHistoryVisible: false,
            sendKeyModalVisible: false,
            lockHistoryModalProps: {
                lock_id: ''
            },
            userManagerModalProps: {
                lock_id: ''
            },
            sendKeyModalProps: {
                owner_uid: '',
                lock_id: ''
            },
            lockBindModalVisible: false,
            lockBindModalProps: {
                lock_id: '',
                owner_uid: ''
            }
        };
        this._setDefaultState(state);
        this.listApiType = api_lock_list;
    }
    async pageDidMount() {
        const result = await StoreListMini.getInfo();
        if (!result) return;
        this._setState({ loading: false });
    }
    showBuyLockModal = () => {
        this.setState({ buyLockModalVisible: true });
    };
    closeBuyLockModal = () => {
        this.setState({ buyLockModalVisible: false });
    };
    showLockBindModal = (owner_uid, lock_id) => {
        this.setState({
            lockBindModalVisible: true,
            lockBindModalProps: {
                owner_uid,
                lock_id
            }
        });
    };
    closeLockBindModal = (refresh = false) => {
        if (refresh === true) this.refresh();
        this.setState({ lockBindModalVisible: false });
    };
    showUserManagerModal = lock_id => {
        this.setState({
            userManagerModalVisible: true,
            userManagerModalProps: {
                lock_id
            }
        });
    };
    closeUserManagerModal = () => {
        this.setState({ userManagerModalVisible: false });
    };
    showLockHistoryModal = lock_id => {
        this.setState({
            lockHistoryVisible: true,
            lockHistoryModalProps: {
                lock_id
            }
        });
    };
    closeLockHistoryModal = () => {
        this.setState({ lockHistoryVisible: false });
    };
    showSendKeyModal = (owner_uid, lock_id) => {
        this.setState({
            sendKeyModalVisible: true,
            sendKeyModalProps: {
                owner_uid,
                lock_id
            }
        });
    };
    closeSendKeyModal = (refresh = false) => {
        if (refresh === true) this.refresh();
        this.setState({ sendKeyModalVisible: false });
    };
    //智能锁取消绑定
    lockUnBind = async (owner_uid, lock_id, house_no) => {
        mConfirm({
            title: '确定要取消绑定该房源吗？',
            titleStyle: { fontSize: 16 },
            width: 300,
            height: 177,
            content: '',
            okText: '是',
            cancelText: '否',
            okClassName: 'primary-btn-ok',
            cancelClassName: 'primary-btn-cancel',
            showTopClose: false,
            onOk: async () => {
                const data = { lock_id, owner_uid, house_no };
                const result = await ApiHelper.requestPost(lock_unbind, data);
                if (result.status) {
                    MModal.success({ title: '操作成功', content: '取消绑定成功' });
                    this.refresh();
                } else {
                    MModal.success({ title: '操作失败', content: result.info });
                }
            },
            onCancel() {}
        });
    };
    render() {
        const { userManagerModalVisible, lockHistoryVisible, buyLockModalVisible, lockHistoryModalProps,
            userManagerModalProps, sendKeyModalVisible, sendKeyModalProps,
            lockBindModalVisible, lockBindModalProps } = this.state;
        const { showBuyLockModal, closeBuyLockModal,
            showUserManagerModal, closeUserManagerModal, showLockHistoryModal, closeLockHistoryModal,
            showSendKeyModal, closeSendKeyModal, showLockBindModal, closeLockBindModal, lockUnBind } = this;

        const oper = (text, record, dataIndex) => (
            <div>
                <a className={style['btn-default']} href="javascript:void(0);" onClick={() => showSendKeyModal(record.lock_owner_uid, record.lock_id)}>发送钥匙</a>
                {/*<a className={style['btn-default']} href="javascript:void(0);">发送密码</a>*/}
                <a className={style['btn-default']} href="javascript:void(0);" onClick={() => showUserManagerModal(record.lock_id)}>用户管理</a>
                <a className={style['btn-default']} href="javascript:void(0);" onClick={() => showLockHistoryModal(record.lock_id)}>开锁记录</a>
            </div>
        );
        const columns = [
            { title: '锁ID', dataIndex: 'lock_id', align: 'middle' },
            { title: '名称', dataIndex: 'address_detail', align: 'middle' },
            { title: '门店', dataIndex: 'store_name', align: 'middle' },
            { title: '经纪人', dataIndex: 'broker_name', align: 'middle' },
            { title: '管理账号', dataIndex: 'lock_owner_account', align: 'middle', render: (text, record, dataIndex) => text == '' ? '账号不存在或已被删除' : text },
            { title: '管理员', dataIndex: 'lock_administrator_name', align: 'middle', render: (text, record, dataIndex) => text == '' ? '账号不存在或已被删除' : text },
            { title: '添加时间', dataIndex: 'lock_create_time', align: 'middle', render: (text, record, dataIndex) => format.timeString(text) },
            { title: '绑定房源', dataIndex: 'is_bind_house', align: 'middle', render: (text, record, dataIndex) =>
                text ?
                    <a className={style['btn-default']} href="javascript:void(0);" onClick={() => lockUnBind(record.lock_owner_uid, record.lock_id, record.house_no)}>取消绑定</a> :
                    <a className={style['btn-default']} href="javascript:void(0);" onClick={() => showLockBindModal(record.lock_owner_uid, record.lock_id)}>绑定</a> },
            { title: '电量', dataIndex: 'electric_quantity', align: 'middle', render: (text, record, dataIndex) => <Battery percent={text / 100}/> },
            { title: '操作', dataIndex: 'a', align: 'middle', render: oper }
        ];
        return (
            <ContentLayout navTitle="智能锁" loading={this.state.loading}>
                <div className={style['top-wrap']}>
                    <div className={style['top-filter']}>
                        <FilterWrapped buyClick={showBuyLockModal} onSubmit={this.getDataListWithFilter} />
                    </div>
                    <MTable columns={columns} dataSource={this.state.dataList} spinning={this.state.spinning}/>
                    <BuyLockModal visible={buyLockModalVisible} onClose={closeBuyLockModal} />
                    <UserManagerModal visible={userManagerModalVisible} onClose={closeUserManagerModal} {...userManagerModalProps}/>
                    <LockHistoryModal visible={lockHistoryVisible} onClose={closeLockHistoryModal} {...lockHistoryModalProps} />
                    <SendKeyModal visible={sendKeyModalVisible} onClose={closeSendKeyModal} {...sendKeyModalProps} />
                    <LockBindModal visible={lockBindModalVisible} onClose={closeLockBindModal} {...lockBindModalProps} />
                    <div className="pagination">
                        {this.state.total > 0 && <Pagination showQuickJumper current={this.state.current_page} pageSize={10} total={this.state.total} onChange={this.pageOnChange} />}
                    </div>
                </div>
            </ContentLayout>
        );
    }
}

export default LockList;